package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckItemMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.CheckItemException;
import com.itheima.pojo.CheckItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    CheckItemMapper checkItemMapper;

    @Override
    public void add(CheckItem checkItem) {
        //直接插入数据库 free mybatis plugin
        checkItemMapper.add(checkItem);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //使用分页插件(告诉mybatis 我要分页)
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //写一个普普通通的查询sql
        checkItemMapper.findPage(queryPageBean.getQueryString());

//        Page<CheckItem> page = checkItemMapper.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void delete(Integer id) {
        //能不能直接删除？？

        //根据检查项id查询是否被别人引用
        Integer count = checkItemMapper.findCountByCheckItemId(id);
        if(count != null && count > 0){
            //存在引用提示用户(自定义异常)
           throw new CheckItemException("存在引用不能删除");
        } else {
            //没有引用直接删除
            checkItemMapper.delete(id);
        }

    }

    @Override
    public CheckItem findById(Integer id) {
        return checkItemMapper.findById(id);
    }

    @Override
    public void edit(CheckItem checkItem) {
        checkItemMapper.edit(checkItem);
    }

    @Override
    public List<CheckItem> findAll() {
        return checkItemMapper.findAll();
    }
}
